package me.spring.cloud.components.starter.rabbitmq.configure;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author luffy
 * @description: 第二mq配置
 * @date 2019-09-03 19:00
 */
@Configuration
@ConditionalOnProperty(prefix = "second.rabbitmq", name = "enable", havingValue = "true")
public class SecondRabbitMqConfiguration {

  private ConnectionFactory rabbitConfiguration(String host, int port, String username, String password) {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setHost(host);
    connectionFactory.setPort(port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
  }

  @Bean("secondRabbitConnectionFactory")
  public ConnectionFactory innerRabbitConfiguration(@Value("${second.rabbitmq.host}") String host,
      @Value("${second.rabbitmq.port}") int port,
      @Value("${second.rabbitmq.username}") String username,
      @Value("${second.rabbitmq.password}") String password) {
    return this.rabbitConfiguration(host, port, username, password);
  }

  @Bean("secondRabbitTemplate")
  public SecondRabbitTemplate consumeRabbitTemplate(
      @Qualifier("secondRabbitConnectionFactory") ConnectionFactory connectionFactory) {
    SecondRabbitTemplate rabbitTemplate = new SecondRabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    return rabbitTemplate;
  }
}
